package com.certificate.tool;

import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.KeyFactory;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.spec.PKCS8EncodedKeySpec;

import javax.net.ssl.SSLContext;

import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.ssl.SSLContexts;
import org.bouncycastle.openssl.PEMKeyPair;
import org.bouncycastle.openssl.PEMParser;

import com.aliyun.configuration.ConfigurationTool;
import com.common.constant.Constant;

/*
 * 设定证书的
 */
public class SetTrustStore {
	
	public static SSLConnectionSocketFactory getSSLConnection() throws Exception {
		 final char[] KEY_STORE_PASSWD = "".toCharArray();
		 //get certificate address
		 
		 Path caCertPath = Paths.get(ConfigurationTool.getProperties(Constant.CA_CERT_PATH));
		 Path clientCertPath = Paths.get(ConfigurationTool.getProperties(Constant.CLIENT_CERT_PATH));
		 Path clientKeyPath = Paths.get(ConfigurationTool.getProperties(Constant.CLIENT_KEY_PATH));
		 
		 final CertificateFactory cf = CertificateFactory.getInstance("X.509");
		 final Certificate caCert = cf.generateCertificate(Files.newInputStream(caCertPath));
		 final Certificate clientCert = cf.generateCertificate(Files.newInputStream(clientCertPath));
		 @SuppressWarnings("resource")
		final PEMKeyPair clientKeyPair = (PEMKeyPair) new PEMParser(Files.newBufferedReader(clientKeyPath, Charset.defaultCharset())).readObject();
		 
		 final PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(clientKeyPair.getPrivateKeyInfo().getEncoded());
		 
		 final KeyFactory kf = KeyFactory.getInstance("RSA");
		 
		 final PrivateKey clientKey = kf.generatePrivate(spec);
		 
		 //设置信任的证书
		 final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
		 trustStore.load(null, null);
		 trustStore.setEntry("ca", new KeyStore.TrustedCertificateEntry(caCert), null);
		 
		 //设置秘钥
		 final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
		 keyStore.load(null, null);
		 keyStore.setCertificateEntry("client", clientCert);
		 keyStore.setKeyEntry("key", clientKey, KEY_STORE_PASSWD, new Certificate[]{clientCert});
		 
		 SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(trustStore,null)
				 .loadKeyMaterial(keyStore, KEY_STORE_PASSWD).build();
		 
		 return new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.getDefaultHostnameVerifier());
		 
	}
	
	
}
